﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace Wangzeran.CodeMaker.GUI.Utils
{
    /// <summary>
    /// 字符串
    /// </summary>
    public class StringHelper
    {

        /// <summary>
        /// 匹配key=value
        /// </summary>
        private const string PATTERN_KEY_VALUE = ".*?=.+?;";

        /// <summary>
        /// 解析Key=Value字符串
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns></returns>
        public static IDictionary<string, string> ParseKeyValues(string str)
        {
            try
            {
                IDictionary<string, string> dic = new Dictionary<string, string>();
                if (str == null)
                {
                    return dic;
                }
                MatchCollection matchs = Regex.Matches(str, PATTERN_KEY_VALUE, RegexOptions.IgnoreCase);
                foreach (Match match in matchs)
                {
                    if (match.Success)
                    {
                        string[] arr = ParseKeyValue(match.Value);
                        dic.Add(arr[0].ToLower().Trim(), arr[1].Trim());
                    }
                }

                return dic;
            }
            catch (Exception ex)
            {	
                throw ex;
            }
        }

        /// <summary>
        /// 解析Key=Value字符串
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns></returns>
        public static string[] ParseKeyValue(string str)
        {
            try
            {
                string[] arr = str.Replace(";", String.Empty).Split('=');
                if (arr.Length < 2)
                {
                    return null;
                }
                return arr;
            }
            catch (Exception ex)
            {	
                throw ex;
            }
        }

    }
}
